package com.ruoyi.coal.modules.publicAPI.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.coal.common.annotation.SysLog;
import com.ruoyi.coal.common.utils.R;
import com.ruoyi.coal.modules.coalpile.domain.CoalYardInfoEntity;
import com.ruoyi.coal.modules.coalpile.domain.RadarEntity;
import com.ruoyi.coal.modules.coalpile.mapper.CoalYardInfoDao;
import com.ruoyi.coal.modules.coalpile.service.CoalYardInfoService;
import com.ruoyi.coal.modules.publicAPI.service.StartRadarService;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Api(value = "publicInfo", tags = {"公开接口"})
@RestController
@RequestMapping({"public"})
@Component("radarStart")
@DataSource(value = DataSourceType.SLAVE)
public class StartRadarController {
    @Autowired
    StartRadarService startRadarService;

    @Autowired
    CoalYardInfoService coalYardInfoService;

    @Autowired
    CoalYardInfoDao coalYardInfoDao;

    @ApiOperation(value = "启动雷达", notes = "启动雷达")
    @PostMapping({"/startRadar/{coalYardId}/{uuid}"})
    @SysLog("调用启动雷达")
    public R startRadar(@PathVariable("coalYardId") Integer coalYardId, @PathVariable("uuid") String uuid) {
        CoalYardInfoEntity coalYardInfo = (CoalYardInfoEntity) this.coalYardInfoService.getById(coalYardId);
        if (coalYardInfo == null)
            return R.error("煤场不存在");
        if (coalYardInfo.getStatus().intValue() != 0)
            return R.error("雷达正在扫描");
        CompletableFuture.runAsync(() -> {
            try {
                Map map = this.startRadarService.startRadar(coalYardId, uuid);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        return R.ok().put("msg", coalYardInfo.getName() + "煤场的雷达启动请求已提交，请等待扫描完成");
    }

    @ApiOperation(value = "定时启动雷达", notes = "定时启动雷达")
    @PostMapping({"/startRadarTimed/{coalYardId}"})
    @SysLog("手动启动雷达")
    public R startRadarTimed(@PathVariable("coalYardId") Integer coalYardId) {
        CoalYardInfoEntity coalYardInfo = (CoalYardInfoEntity) this.coalYardInfoService.getById(coalYardId);
        if (coalYardInfo == null)
            return R.error("煤场不存在");
        if (coalYardInfo.getStatus().intValue() != 0)
            return R.error("雷达正在扫描");
        CompletableFuture.runAsync(() -> {
            try {
                Map map = this.startRadarService.startRadarTimed(coalYardId);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        return R.ok().put("msg", coalYardInfo.getName() + "煤场的雷达启动请求已提交，请等待扫描完成");
    }

    @PostMapping({"/startRadars"})
    @SysLog("手动批量启动雷达")
    public R startRadars(@RequestBody Integer[] coalYardIds) throws InterruptedException {
        Arrays.sort((Object[]) coalYardIds);
        if (coalYardIds.length == 0)
            return R.error().put("msg", "请选择要启动的煤场");
        List<Integer> availableCoalYardIds = new ArrayList<>();
        List<Integer> unavailableCoalYardIds = new ArrayList<>();
        HashMap<Integer, Integer> coalYardIdMaps = new HashMap<>();
        Integer[] arrayOfInteger;
        int j;
        byte b;
        for (arrayOfInteger = coalYardIds, j = arrayOfInteger.length, b = 0; b < j; ) {
            int coalYardId = arrayOfInteger[b].intValue();
            CoalYardInfoEntity coalYardInfo = (CoalYardInfoEntity) this.coalYardInfoService.getById(Integer.valueOf(coalYardId));
            if (coalYardInfo.getStatus().intValue() == 0) {
                availableCoalYardIds.add(Integer.valueOf(coalYardId));
            } else {
                unavailableCoalYardIds.add(Integer.valueOf(coalYardId));
            }
            b++;
        }
        for (int i = 0; i < availableCoalYardIds.size(); i++)
            coalYardIdMaps.put(Integer.valueOf(i), availableCoalYardIds.get(i));
        for (Map.Entry<Integer, Integer> entry : coalYardIdMaps.entrySet())
            this.startRadarService.startRadars(entry);
        if (unavailableCoalYardIds.size() == 0)
            return R.ok().put("msg", this.coalYardInfoService.getCoalYardNameByIds(availableCoalYardIds) + "煤场的雷达启动请求已提交，请等待扫描完成");
        return R.ok().put("msg", this.coalYardInfoService.getCoalYardNameByIds(availableCoalYardIds) + "煤场的雷达启动请求已提交，请等待扫描完成"+ this.coalYardInfoService.getCoalYardNameByIds(unavailableCoalYardIds) + "煤场的雷达正在扫描中");
    }

    @ApiOperation(value = "雷达自检", notes = "雷达自检")
    @PostMapping({"/checkRadar"})
    public R checkRadar(@RequestParam("ptzCom") String ptzCom, @RequestParam("ip1") String ip1, @RequestParam("ip2") String ip2) {
        RadarEntity one = (RadarEntity) this.startRadarService.getOne((Wrapper) ((QueryWrapper) ((QueryWrapper) (new QueryWrapper()).eq("ptz_com", ptzCom)).eq("ip1", ip1)).eq("ip2", ip2));
        if (ObjectUtil.isNull(one))
            return R.error("该雷达信息不正确");
        Map<String, Object> result = this.startRadarService.radarCheck(ptzCom, ip1, ip2);
        if (result.get("code").equals("200"))
            return R.ok("雷达自检正常");
        return R.error("雷达自检出现异常");
    }

    @ApiOperation(value = "云台自检", notes = "云台自检")
    @PostMapping({"/checkSerial"})
    public R checkRadar(@RequestParam("port") String port) {
        Map<String, Object> result = this.startRadarService.checkSerial(port);
        if (result.get("code").equals("200"))
            return R.ok("云台自检正常");
        return R.error("云台自检出现异常");
    }

    @ApiOperation(value = "导入点云计算", notes = "")
    @PostMapping({"/importCloud"})
    public R importCloud(@RequestParam("filePath") String filePath) {
        CoalYardInfoEntity coalYardInfoEntity = (CoalYardInfoEntity) this.coalYardInfoDao.selectOne((Wrapper) (new QueryWrapper()).eq("name", "导入料堆"));
                Map < String, Object > result = this.startRadarService.importCloud(coalYardInfoEntity.getId(), filePath);
        if (result.get("code").equals("200"))
            return R.ok("计算成功");
        return R.error("计算出现异常");
    }

    @ApiOperation("用于扫描完成后分割计算数据")
    @PostMapping({"/cutUpAndMeasure"})
    public R cutUpAndMeasure(@RequestParam("coalYardId") Integer coalYardId) {
        if (((CoalYardInfoEntity) this.coalYardInfoService.getById(coalYardId)).getStatus().intValue() != 0)
            return R.error("雷达正在扫描计算中，请等待扫描完成");
        CompletableFuture.runAsync(() -> this.startRadarService.cutUpAndMeasure(coalYardId));
        return R.ok("计算任务已提交，请等待计算完成");
    }

    @ApiOperation("向雷达串口发送命令")
    @PostMapping({"/sendCommand"})
    public R sendCommand(@RequestParam("command") String command, @RequestParam("coalYardId") Integer coalYardId) {
        JSONObject response = this.startRadarService.sendCommand(command, coalYardId);
        if (response.get("code").equals(Integer.valueOf(200)))
            return R.ok();
        return R.error("雷达正在扫描中");
    }
}

